<template>
  <div class="overflow">
    <table class="layui-table">
      <thead>
        <tr>
          <th>帖子标题</th>
          <th>状态</th>
          <th>结贴</th>
          <th>发表时间</th>
          <th>数据</th>
          <th>操作</th>
        </tr>
      </thead>
      <tbody>
        <tr v-for="(item,index) in list" :key="'post'+index">
          <td><router-link class="link" :to="{name: 'detail',params: {tid: item._id}}">{{item.title}}</router-link></td>
          <td>{{item.status === 1? '关闭': '开启'}}</td>
          <td :class="{orange: item.isEnd===1}">{{item.isEnd === 1? '已结': '未结'}}</td>
          <td>{{item.created | formatDate}}</td>
          <td>{{item.reads}}阅/{{item.answer}}答</td>
          <td>
            <div class="layui-btn layui-btn-xs" :class="{'layui-btn-disabled':item.isEnd === 1}" @click="goToEdit(item)">编辑</div>
            <div class="layui-btn layui-btn-xs layui-btn-danger" :class="{'layui-btn-disabled':item.isEnd === 1}" @click="deletePost(item,index)">删除</div>
          </td>
        </tr>
      </tbody>
    </table>
    <Pagination v-show="list.length > 0 && total > 0" @changeCurrent="changeCurrent" :total="total" :size="limit" :current="current" :showEnd="false" :showType="'icon'"></Pagination>
  </div>
</template>

<script>
import { getMyPost, deleteMyPost } from '@/api/user'
import Pagination from '@/components/modules/pagination/pagination'
export default {
  name: 'mypost',
  components: {
    Pagination
  },
  data () {
    return {
      total: 0,
      list: [],
      current: 0,
      limit: 10
    }
  },
  mounted () {
    this.getpost()
  },
  methods: {
    changeCurrent (val, size) {
      this.current = val
      this.limit = size
      this.getpost()
    },
    async getpost () {
      const res = await getMyPost({ uid: this.$store.state.userInfo._id, page: this.current, limit: this.limit })
      if (res.code === 200) {
        this.list = res.data
        this.total = res.total
      }
    },
    goToEdit (item) {
      if (item.isEnd === 1) {
        this.$pop('shake', '已结贴，无法编辑')
      } else {
        this.$router.push({
          name: 'edit',
          params: {
            page: item,
            tid: item._id
          }
        })
      }
    },
    // 删除帖子
    deletePost (item, index) {
      if (item.isEnd === 1) {
        this.$pop('shake', '已结贴，无法删除')
        return
      }
      this.$confirm('确定要删除该帖子吗？', async () => {
        const res = await deleteMyPost({ tid: item._id })
        if (res.code === 200) {
          this.list.splice(index, 1)
        }
        this.$pop('', res.msg)
      })
    }
  }
}
</script>

<style lang="scss" scoped>
.overflow{
  overflow: auto;
}
.layui-table {
  min-width: 680px;
  th,td{
    text-align: center;
    &:first-child {
      text-align: left;
    }
  }
}
.link{
  color: #01AAED;
}
</style>
